<template>
  <div>
    <el-row>
      <el-tabs type="border-card">
        <el-tab-pane label="风险传播">
          <div class="btn">
            <div class="tips" v-if="this.dataset != ''">
              当前选择的数据集: {{ dataset }}
            </div>
            <div
              class="tips"
              style="font-size: 15px; margin-top: 10px"
              v-if="this.dataset == ''"
            >
              未选择数据集，请前往风险溯源进行前置操作
            </div>
            <el-select
              v-model="selectedNode"
              placeholder="请选择待传播的溯源节点"
              style="width: 200px; margin-right: 10px"
              :disabled="!sourceData.length"
            >
              <el-option
                v-for="(item, index) in sourceData"
                :key="index"
                :label="item.nodeName"
                :value="item.id"
              />
            </el-select>
            <el-button
              type="primary"
              :disabled="
                startFlag || selectedNode === null || sourceData.length === 0
              "
              :loading="startFlag"
              style="width: 100px"
              @click="start"
            >
              开始
            </el-button>
          </div>
          <div class="content1">
            <!-- 固定最优路径和评分 -->
            <div v-if="fixedRiskPath.length">
              <div style="font-weight: bold; margin-bottom: 10px">
                最优传播路径：
              </div>
              <div style="margin-bottom: 10px">
                {{ fixedRiskPath.join(" → ") }}
              </div>
              <div style="font-weight: bold; margin-bottom: 5px">
                所有路径评分：
              </div>
              <el-table
                :data="fixedPathScores"
                border
                style="width: 100%; margin-bottom: 15px"
                height="300"
              >
                <el-table-column
                  prop="rank"
                  label="排名"
                  width="80"
                  align="center"
                />
                <el-table-column prop="path" label="传播路径" min-width="200">
                  <template #default="{ row }">
                    {{ row.path.join(" → ") }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="score"
                  label="评分"
                  width="120"
                  align="center"
                >
                  <template #default="{ row }">
                    {{ row.score.toFixed(2) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 当前节点路径 -->
            <div v-if="riskPath.length">
              <div style="font-weight: bold; margin-bottom: 10px">
                当前传播路径：
              </div>
              <div style="margin-bottom: 10px">{{ riskPath.join(" → ") }}</div>
            </div>
            <div v-else>
              <div style="color: #999; text-align: center; padding: 20px">
                暂无当前节点传播路径数据，请先选择节点并点击"开始"按钮
              </div>
            </div>
          </div>
          <div
            ref="networkContainer"
            style="height: 500px; width: 100%; margin-top: 20px"
          ></div>
        </el-tab-pane>
      </el-tabs>
    </el-row>
  </div>
</template>

<script>
import http from "@/utils/request"
import { DataSet,Network } from "vis";
import { mapGetters, mapMutations } from "vuex";

export default {
  data() {
    return {
      startFlag: false,
      completedFlag: false,
      riskPath: [],
      topScores: [], // 新增评分数据
      selectedNode: null,
      sourceData: [],
      nodes: new DataSet([]),
      edges: new DataSet([]),
      links: [],
      network: null,  // 添加network到data中
      pathScores: [], // 新增路径评分表格数据
      fixedRiskPath: [],  // 新增固定最优路径
      fixedPathScores: [],  // 新增固定路径评分
    };
  },
  computed: {
    ...mapGetters({
      dataset: "getDataset",
      AllNodes: "getAllNodes",
      AllEdges: "getAllEdges",
    }),
  },
  methods: {
    ...mapMutations(["setAllNodes", "setAllEdges"]),


    async getSourceData() {
      try {
        // const res = await request({
        //   url: "/spread/infected_nodes",
        //   method: "get",
        // });
        const res =await http.get('/spread/infected_nodes')
        this.sourceData = res.data.map((item) => ({
          id: item.ID+1,
          nodeName: item.NodeName,
        }));
      } catch (err) {
        console.error("风险溯源数据加载失败:", err);
        this.$message.error("数据加载失败");
      }
    },

    // 在start方法中更新pathScores数据
    async start() {
      this.startFlag = true;
      this.riskPath = [];
      this.pathScores = [];

      try {
          if (!this.selectedNode) {
              throw new Error('请先选择节点');
          }

          http.get("/spread/riskpath", {params: {
                  nodeId: this.selectedNode // 确保传递的是正确的ID
              }}
          ).then((res)=>{
            console.log('API响应数据:', res.data); // 添加调试日志
            console.log('Vuex中的AllNodes:', this.AllNodes); // 添加调试日志

            if (!res.data || !res.data.riskPath || !this.AllNodes) {
              throw new Error('数据格式错误或节点数据未加载');
            }

            const idToName = (idPath) => {
              if (!Array.isArray(idPath)) return [];
              return idPath.map(id => {
                const node = this.AllNodes.find(n => n.id == id);
                console.log(`转换节点 ${id}:`, node); // 添加调试日志
                return node ? node.nodeName : `未知节点(${id})`;
              });
            };

            const topPath = res.data.riskPath;
            this.riskPath = idToName(topPath);

            if (res.data.allPaths && res.data.scores) {
              this.pathScores = res.data.allPaths.map((path, index) => ({
                rank: index + 1,
                path: idToName(path),
                score: res.data.scores[index]
              }));
              console.log('处理后的pathScores:', this.pathScores); // 添加调试日志
            }

            this.links = topPath
                .map(id => this.AllNodes.find(node => node.id == id)?.id || 0)
                .filter(id => id !== 0);

            this.reloadMap();
            this.$message.success("风险路径获取成功");
          })


      } catch (err) {
          console.error("获取风险路径失败:", err);
          this.$message.error(`获取路径失败: ${err.message}`);
          this.riskPath = [`获取路径失败: ${err.message}`];
          this.links = [];
      } finally {
          this.startFlag = false;
      }
    },
    reloadMap() {
      this.nodes.clear();
      this.edges.clear();
      this.AllNodes.forEach((item) => {
        if (this.links.includes(item.id)) {
          this.nodes.add({
            id: item.id,
            label: item.nodeName,
            color: {
              border: "#FF0000",
              background: "#FF0000",
              highlight: { background: "#FF0000", border: "#FF0000" },
              selected: { background: "#FF0000", border: "#FF0000" },
            },
            font: { color: "white" },
          });
          this.riskPath.push(item.nodeName);
        } else {
          this.nodes.add({
            id: item.id,
            label: item.nodeName,
            color: {
              border: "#0000FF",
              background: "#0000FF",
              highlight: { background: "#0000FF", border: "#0000FF" },
              selected: { background: "#0000FF", border: "#0000FF" },
            },
            font: { color: "white" },
          });
        }
      });
      this.AllEdges.forEach((item) => {
        if (this.links.includes(item.from) && this.links.includes(item.to)) {
          this.edges.add({
            from: item.from,
            to: item.to,
            color: {
              color: "#FF0000",
              highlight: "#FF0000",
            },
          });
        } else {
          this.edges.add({
            from: item.from,
            to: item.to,
            color: {
              color: "#0000FF",
              highlight: "#0000FF",
            },
          });
        }
      });
      this.initNetwork();
    },
    initNetwork() {
      const container = this.$refs.networkContainer;
      this.network = new Network(
        container,
        { nodes: this.nodes, edges: this.edges },
        { physics: true }
      );
    },
        // 新增方法：加载固定路径
    async loadFixedPaths() {
      try {
        http.get("/spread/fixed_riskpath").then((res)=>{
          if (res.data) {
            // 处理最优路径 - 前端传回[['127037','127109','127076','127148']]，需转换为单层数组
            if (res.data.fixedRiskPath) {
              this.fixedRiskPath = Array.isArray(res.data.fixedRiskPath[0])
                  ? res.data.fixedRiskPath[0]
                  : res.data.fixedRiskPath;
            }

            // 处理所有路径和评分
            if (res.data.fixedAllPaths && res.data.fixedScores) {
              this.fixedPathScores = res.data.fixedAllPaths.map((path, index) => ({
                rank: index + 1,
                path: path,  // 表格显示仍使用节点名称
                score: res.data.fixedScores[index] || 0
              }));
            }
          }
        })


      } catch (err) {
        console.error("加载固定路径失败:", err);
        this.$message.error("加载固定路径失败");
      }
    },
    // 新增idToName方法
    idToName(idPath) {
        if (!Array.isArray(idPath)) return [];
        return idPath.map(id => {
            const node = this.AllNodes.find(n => n.id == id);
            return node ? node.nodeName : `未知节点(${id})`;
        });
    },
  },
  mounted() {
    this.getSourceData();
    this.initNetwork();
    this.loadFixedPaths();
  }
}
</script>
